from base import *
import base

class td(tag):
    def __init__(self, childs=[]):
        tag.__init__(self, childs)
    
    def loadCSS(self):
        tag.loadCSS(self)
        head = self.findRelative(objType="head")
        if "width" in dir(self):
            self.widthCSS(head)

    def widthCSS(self, head): # Doesn't work
        c_name = base.getClassName("table")
        self.setClass(c_name)
        head.addCSS(base.css("td.%s { width:%i; }" %
                             (c_name, self.width)))

    def setWidth(self, w, wrapText=True):
        self.width = w

    def setSpan(self, s):
        self.addTagOpt("colspan", s)


class tr(tag):
    def __init__(self, childs=[]):
        tag.__init__(self, []) # Weird bug fix

    def fromList(self, lst):
        for ele in lst:
            if "toHTML" in dir(ele):
                self.addChild(td([ele]))
            else:
                self.addChild(td([string(str(ele))]))
        return self


class table(tag):
    def __init__(self, childs=[]):
        tag.__init__(self, []) # Weird bug fix

    def fromList(self, lst):
        for row in lst:
            self.addChild(tr().fromList(row))
        return self
    
    def getClassName(self):
        return "table"

    def setColumnWidth(self, c, w):
        self.addChild(base.string("<col width=\"%i\">" % w))


    

import _mysql

def getDataInList(db, query):
        db.query(query)
        r=db.store_result()
        data = []
        row = r.fetch_row()
        while row:
            data.append(list(row[0]))
            row = r.fetch_row()
        return data

class datatable(table):
    def __init__(self, password, database, query,
                 _host="localhost", _user="root",
                 headers=[], handler=None):
        table.__init__(self)
        db = _mysql.connect(host=_host, user=_user,
                            passwd=password, db=database)

        data = getDataInList(db, query)

        if headers:
            data = [headers] + data
        if handler:
            data = handler(data)
        self.fromList(data)

import csv
def csvToList(file_name):
    f = open(file_name, 'r')
    lst = []
    line_reader = csv.reader(f, delimiter=',', quotechar='"')
    for row in line_reader:
        lst.append(row)
    return lst
            
        
class csv_table(table):
    def __init__(self, csv_fname, headers=[],
                 handler=None):
        table.__init__(self, [])
        data = csvToList(csv_fname)

        if headers:
            data = [headers] + data
        if handler:
            data = handler(data)
        self.fromList(csvToList(csv_fname))

